import React, { useEffect } from 'react';
import moment from 'moment';
import { Button, DatePicker, Select, Space, Spin } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjChart, TjTable } from '@/pages/ETrade/components';

import { getSectionTrend, getChannelNameList } from './services.js';
import { fmtDataSource, tableColumns, tableColumnsHlj, fmtHljDataSource } from './helper';
import styles from './index.less';
import { useThemeChange } from '@/hooks';

const getDateRange = () => {
  return [moment().add(-7, 'day'), moment().add(-1, 'day')];
};

export default ({ power }) => {
  /** data */
  const [state, setState] = useTRState({
    // form
    marketItem: power[0],
    dates: getDateRange(),
    sectionName: null,
    // 通道
    loadingSec: false,
    secMap: null, // 数据
    secOptions: [],
    heilongjiangLimitOptions: [
      { label: '正向限额', value: 'positiveLimit' },
      { label: '反向限额', value: 'reverseLimit' },
      { label: '正向越限时间段数', value: 'positiveBeyondLimitNumber' },
      { label: '反向越限时间段数', value: 'reverseBeyondLimitNumber' },
    ],
    heilongjiangSectionNameOptions: [],
    heilongjiangSectionName: '',
    heilongjiangLimitIndex: 'positiveLimit',
    secType: 'importance', // 类型
    // result
    loading: true,
    dataSource: [],
    tableData: [],
    chartOption: null,
  });
  const { theme } = useThemeChange();

  useEffect(() => {
    _fetchSections(power[0], 'isFirst');
  }, []);

  useEffect(() => {
    setTimeout(() => {
      const { chartOption } = fmtDataSource(state.dataSource);
      setState({
        chartOption,
      });
    }, 1);
  }, [theme]);

  /** apis */
  const _fetchData = async (params) => {
    // 数据
    setState({ loading: true });
    const res = await getSectionTrend(params);
    if (params.marketId === 'PDBLJ') {
      const dataSource = res?.data?.data || {};
      const result = fmtHljDataSource(dataSource, params);

      setState({
        ...result,
        dataSource,
        loading: false,
      });
    } else {
      const dataSource = res?.list || [];
      const result = fmtDataSource(dataSource);

      if (params.isAppointedDay === true) {
        const date = Object.keys(dataSource?.[0]?.pointData || {})?.[0];
        if (date) {
          state.dates = [moment(date), moment(date)];
        }
      }
      setState({
        ...result,
        dataSource,
        loading: false,
        dates: state.dates,
      });
    }
  };

  const _fetchSections = async (d, type) => {
    // 通道
    setState({ loadingSec: true });
    const res = await getChannelNameList({
      marketId: d.marketId,
      provinceId: d.provinceId,
    });

    if (d.marketId === 'PDBLJ') {
      let heilongjiangSectionNameOptions = [],
        heilongjiangSectionName = '';
      heilongjiangSectionNameOptions = res?.data.map((key) => ({
        label: key,
        value: key,
      }));
      heilongjiangSectionName = heilongjiangSectionNameOptions?.[0]?.value || null;
      setState({
        heilongjiangSectionNameOptions,
        heilongjiangSectionName,
        loadingSec: false,
      });
      type === 'isFirst' && _onFinish(type);
    } else {
      const secMap = res?.resultMap || {};
      for (const k in secMap) {
        secMap[k] = secMap[k]?.length ? secMap[k].map((x) => ({ label: x, value: x })) : [];
      }
      const secOptions = secMap?.importance || [];
      const sectionName = secOptions?.[0]?.value || null;
      state.sectionName = sectionName;
      setState({
        secMap,
        secOptions,
        sectionName,
        secType: 'importance', // 类型
        loadingSec: false,
      });
      type === 'isFirst' && _onFinish(type);
    }
  };

  useEffect(() => {
    if (state.heilongjiangSectionName && state.heilongjiangLimitIndex) _onFinish();
  }, [state.heilongjiangSectionName, state.heilongjiangLimitIndex]);

  /** methods */
  const _onFinish = (type) => {
    // 提交查询表单
    let formValue = {};
    if (state.marketItem.marketId !== 'PDBLJ') {
      formValue = {
        startDate: state.dates[0].format('YYYY-MM-DD'), // 开始日期
        endDate: state.dates[1].format('YYYY-MM-DD'), // 结束日期
        marketId: state.marketItem.marketId, // 交易中心编码
        provinceId: state.marketItem.provinceId, // 省份ID
        sectionName: state.sectionName || '',
        isAppointedDay: !!type,
      };
    } else {
      formValue = {
        startDate: state.dates[0].format('YYYY-MM-DD'), // 开始日期
        endDate: state.dates[1].format('YYYY-MM-DD'), // 结束日期
        marketId: state.marketItem.marketId, // 交易中心编码
        sectionName: state.heilongjiangSectionName || '',
        limitIndex: state.heilongjiangLimitIndex || '',
      };
    }
    _fetchData(formValue);
  };

  const _onReset = async () => {
    // 重置
    const secOptions = state.secMap?.importance || [];
    const sectionName = secOptions?.[0]?.value || null;
    setState({
      sectionName,
      secOptions,
      secType: 'importance', // 类型
      marketItem: power[0],
      dates: getDateRange(),
      heilongjiangLimitIndex: 'positiveLimit',
      heilongjiangSectionName: state.heilongjiangSectionNameOptions?.[0]?.value || '',
    });
    if (power[0].marketId !== 'PDBLJ') {
      _onFinish();
    }
  };

  const onchangeMarket = (e, marketItem) => {
    setState({
      marketItem,
      sectionName: null,
      secMap: null, // 数据
      secOptions: [],
      secType: 'importance', // 类型
    });
    _fetchSections(marketItem);
  };

  const onchangeSectionType = (secType) => {
    const secOptions = state.secMap?.[secType] || [];
    const sectionName = secOptions?.[0]?.value || null;
    setState({
      secType,
      secOptions,
      sectionName,
    });
  };

  /** render */
  const pipeline = useTablePipeline()
    .input({ columns: tableColumns, dataSource: state.tableData })
    .primaryKey('id')
    .use(features.rowGrouping({ defaultOpenAll: true }))
    .appendRowPropsGetter((record) => {
      const color = !!record.groupTitle
        ? '#2D3133'
        : !!record.overloaded && record.overloaded !== '-'
        ? '#382A2C'
        : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  /** render */
  const pipelineHlj = useTablePipeline()
    .input({ columns: tableColumnsHlj, dataSource: state.tableData })
    .primaryKey('id');

  const _renderMain = () => {
    //if (!state.dataSource.length) return <TRDefault type="emptysm" />;
    if (state.marketItem.value === 'PDBLJ') {
      return (
        <div className={styles.mainColoumn}>
          <div className={styles.chart}>
            <div className={styles.title}>
              <span>断面趋势图</span>
              <span className={styles.selects}>
                <Select
                  style={{ width: 140 }}
                  value={state.heilongjiangSectionName}
                  options={state.heilongjiangSectionNameOptions}
                  showArrow
                  showSearch
                  onChange={(heilongjiangSectionName) => setState({ heilongjiangSectionName })}
                />
                <Select
                  style={{ width: 200 }}
                  value={state.heilongjiangLimitIndex}
                  options={state.heilongjiangLimitOptions}
                  optionFilterProp="label"
                  showSearch
                  showArrow
                  onChange={(limitIndex) => setState({ heilongjiangLimitIndex: limitIndex })}
                />
              </span>
            </div>
            <div className={styles.chartIn}>
              <TjChart option={state.chartOption} />
            </div>
          </div>
          <div className={styles.table}>
            <div className={styles.title}>断面明细表</div>
            <div className={styles.tableIn}>
              <TjTable useVirtual="auto" {...pipelineHlj.getProps()} />
            </div>
          </div>
        </div>
      );
    }
    return (
      <div className={styles.mainInner}>
        <div className={styles.chart}>
          <div className={styles.title}>忻州主变-断面趋势图</div>
          <div className={styles.chartIn}>
            <TjChart option={state.chartOption} />
          </div>
        </div>
        <div className={styles.table}>
          <div className={styles.title}>忻州主变-断面明细表</div>
          <div className={styles.tableIn}>
            <TjTable useVirtual="auto" {...pipeline.getProps()} />
          </div>
        </div>
      </div>
    );
  };

  return (
    <Spin spinning={state.loadingSec || state.loading} wrapperClassName={styles.content}>
      <div className={styles.head}>
        <Space size={16} wrap>
          <Select
            style={{ width: 200 }}
            value={state.marketItem.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={onchangeMarket}
          />
          <DatePicker.RangePicker
            style={{ width: 216 }}
            value={state.dates}
            separator="-"
            format={'YYYYMMDD'}
            disabledDate={(v) => v > moment()}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
          />
          {state.marketItem.value !== 'PDBLJ' && (
            <>
              <Select
                style={{ width: 140 }}
                value={state.secType}
                options={[
                  { label: '是重要通道', value: 'importance' },
                  { label: '非重要通道', value: 'unimportance' },
                ]}
                showArrow
                onChange={onchangeSectionType}
              />
              <Select
                style={{ width: 200 }}
                value={state.sectionName}
                options={state.secOptions}
                disabled={!state.secOptions.length}
                placeholder={state.loadingSec ? '正在加载断面数据' : '暂无断面数据'}
                showSearch
                showArrow
                onChange={(sectionName) => setState({ sectionName })}
              />
            </>
          )}

          <Space size={16}>
            <Button
              style={{ width: 98, height: 32 }}
              type="primary"
              onClick={() => {
                _onFinish();
              }}
            >
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
      </div>
      <div className={styles.main}>{_renderMain()}</div>
    </Spin>
  );
};
